package com.tommy.jiami.utils.task;

import android.os.*;
import com.tommy.jiami.utils.*;
import android.content.*;
import android.app.*;
import com.tommy.jiami.*;
import java.io.*;
import android.widget.*;

public class CryptMediaTask extends AsyncTask<Media,Object,Object>
{
	Context context;
	ProgressDialog dialog;
	int type;
	int index;
	
	public CryptMediaTask(Context context,int type,int index){
		this.context=context;
		this.type=type;
		this.index=index;
	}
	
	@Override
	protected void onPreExecute()
	{
		dialog=new ProgressDialog(context);
		dialog.setTitle(Utils.getString(R.string.media_dialog_title,Utils.getCryptType(type)));
		dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		dialog.setCanceledOnTouchOutside(false);
		dialog.setButton("隐藏", new DialogInterface.OnClickListener(){
				@Override
				public void onClick(DialogInterface dialog, int what)
				{
					dialog.cancel();
				}						
		});
		dialog.show();
		super.onPreExecute();
	}
	
	@Override
	protected Object doInBackground(Media[] params)
	{
		try
		{
			File directory=new File(context.getFilesDir().toString() + "/jiamis");
			if(!directory.exists())directory.mkdirs();
			String userPwd=Utils.getUserPassword();
			for (int i=0;i < params.length;i++)
			{
				Media media=params[i];
				publishProgress(media.getFile().toString(),i+1, params.length);
				if (type == Crypt.TYPE_ENCRYPT)
				{
					String fromPath=media.getFile().toString();
					String toPath=directory +File.separator+ Crypt.encryptString(fromPath, userPwd);
					Crypt.encryptFile(fromPath, toPath, userPwd, true);
					context.getContentResolver().delete(media.getFromUri(),null,null);
				}
				else
				{
					String fromPath=media.getFile().toString();
					String toPath=Crypt.decryptString(Utils.getFileName(fromPath),userPwd);
					Crypt.decryptFile(fromPath,toPath,userPwd,true);
				}
			}
			
			context.sendBroadcast(new Intent(Constants.ACTION_CRYPT_OK).putExtra("index",index));
			return true;
		}
		catch (Exception e)
		{return e;}
	}

	@Override
	protected void onProgressUpdate(Object[] values)
	{
		dialog.setMessage(Utils.getString(R.string.media_dialog_message,values[0],values[1],values[2],Utils.getCryptType(type)));
		super.onProgressUpdate(values);
	}
	
	@Override
	protected void onPostExecute(Object result)
	{
		dialog.cancel();
		Utils.showToast(R.string.media_dialog_ok,Utils.getCryptType(type));
		super.onPostExecute(result);
	}
	

}
